package ms.pc.inf;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.NameValuePair;


import android.util.Log;

public class DBConnectivity {

	public static String loggedInUserName="";
	public static double loggedInUserLongitude;
	public static double loggedInUserLatitude;
	public static double eventLongitude;
	public static double eventLatitude;
	public static String selectedEventID;
	public static ArrayList<EventInfo> arrUserEvents =  new ArrayList<EventInfo>();
	public static ArrayList<EventInfo> arrAllEvents =  new ArrayList<EventInfo>();
	public static String[] listUsersByEvent;
	private boolean boolAuthentication = false;

	public boolean authenticate(String user,String pass)
	{
		String result = null;
		InputStream is = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://192.168.0.106/infinity/and_login.php");
			nameValuePairs.add(new BasicNameValuePair("myusername",user));
			nameValuePairs.add(new BasicNameValuePair("mypassword",pass));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
		result = convertResopnseToString(is);

		parseJSONForAuthentication(result);

		return boolAuthentication;

	}

	public void getUsersByEvents()
	{
		String result = null;
		InputStream is = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://192.168.0.106/infinity/and_all_usersbyevent.php");
			nameValuePairs.add(new BasicNameValuePair("event_id",selectedEventID));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
		result = convertResopnseToString(is);

		parseJSONForUserByEvents(result);

	}

	public void getAllEventsByUser()
	{
		String result = null;
		InputStream is = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://192.168.0.106/infinity/and_all_user_events.php");
			nameValuePairs.add(new BasicNameValuePair("myusername",loggedInUserName));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
		result = convertResopnseToString(is);

		parseJSONForAllEvents("User",result);//parseJSONForEventsByUser(result);


	}

	public void getAllEvents()
	{
		String result = null;
		InputStream is = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://192.168.0.106/infinity/and_all_events.php");
			nameValuePairs.add(new BasicNameValuePair("myusername",loggedInUserName));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
		result = convertResopnseToString(is);

		parseJSONForAllEvents("All",result);

	}

	public void confirmAttendingEvent()
	{
		InputStream is = null;
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://192.168.0.106/infinity/and_register_event.php");
			nameValuePairs.add(new BasicNameValuePair("myusername",loggedInUserName));
			nameValuePairs.add(new BasicNameValuePair("event_id",selectedEventID));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
		convertResopnseToString(is);

		//parseJSONForAllEvents("User",result);

		//getAllEvents();



	}

	public String convertResopnseToString(InputStream input)
	{
		String result = "";
		StringBuilder sb=null;
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line="0";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			input.close();
			result=sb.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public void parseJSONForAuthentication(String input)
	{
		try{
			JSONObject json_data= new JSONObject(input);
			boolAuthentication = json_data.getBoolean("status");
			if(boolAuthentication)
			{
				loggedInUserName=json_data.getString("username");	
			}else
			{
				loggedInUserName="";
			}
		}
		catch(JSONException e1){
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}
	public void parseJSONForAllEvents(String functionName,String input)
	{
		JSONArray jArray;
		EventInfo objEventfInfo;
		try{
			jArray = new JSONArray(input);
			JSONObject json_data=null;
			ArrayList<EventInfo> arrEventList = new ArrayList<EventInfo>();
			for(int i=0;i<jArray.length();i++){
				objEventfInfo = new EventInfo();
				json_data = jArray.getJSONObject(i);
				objEventfInfo.setEventID(json_data.getString("event_ID"));
				objEventfInfo.setEventName(json_data.getString("event_name"));
				objEventfInfo.setEventDate(json_data.getString("start_date"));
				objEventfInfo.setLongitude(json_data.getDouble("longitude"));
				objEventfInfo.setLatitude(json_data.getDouble("latitude"));

				arrEventList.add(objEventfInfo);
			}
			if(functionName.equals("User"))
			{
				arrUserEvents = new ArrayList<EventInfo>();
				arrUserEvents = arrEventList;
			}else
			{
				arrAllEvents = new ArrayList<EventInfo>();
				arrAllEvents = arrEventList;
			}
		}
		catch(JSONException e1){
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}
	public void parseJSONForUserByEvents(String input)
	{
		JSONArray jArray;
		try{
			jArray = new JSONArray(input);
			JSONObject json_data=null;
			listUsersByEvent = new String[jArray.length()];
			for(int i=0;i<jArray.length();i++){
				json_data = jArray.getJSONObject(i);
				listUsersByEvent[i] = json_data.getString("username");
			}
		}
		catch(JSONException e1){
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}
	


}
